import random

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response

from rest_framework.views import APIView

from users.models import User
from verifications import constants
from meiduo_mall.libs.yuntongxun.sms import CCP
import logging

logger = logging.getLogger('django')


# 短信验证
# API: GET /sms_codes/(?P<mobile>1[3-9]\d{9})/
class SMSCodeView(APIView):
    def get(self, request, mobile):
        '''
        获取手机验证码
        1. 随机生产六位数字作为短信验证码
        2. 在radis中存储短信验证码
        3. 利用云通讯发送验证码
        4. 返回响应 短信发送成功
        '''

        # 获取radis对连接
        radis_conn = get_redis_connection('verify_codes')
        # 判断60s内是否给该用户发够短信
        send_flag = radis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            return Response({'massage': '发送短信过于频繁'}, status=status.HTTP_400_BAD_REQUEST)

        #
        # 1. 随机生产六位数字作为短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print('==============', sms_code, mobile)

        # 2. 在radis中存储短信验证码


        # 利用管道执行radis命令
        pl = radis_conn.pipeline()
        # 保存数据  手机号 过期时间  验证码
        # radis_conn.set(key, value, expries)
        # radis_conn.setex(key, experies, value)
        # 为管道中添加命令
        pl.setex('sme_%s' % mobile, constants.SMS_CODES_REDIS_EXPIRES, sms_code)

        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 一次执行
        pl.execute()

        # 3. 利用云通讯发送验证码
        # 创建对象

        expires = constants.SMS_CODES_REDIS_EXPIRES // 60

        # 调用云通讯
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code, expires)

        # 4. 返回响应 短信发送成功
        return Response({'massage': 'OK'})

        # return Response(mobile)
